
package com.yx.cloud.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.aliyun.aligeniessp_1_0.models.AuthLoginWithAligenieUserInfoGeneratedByPhoneNumberResponseBody;
import com.aliyun.aligeniessp_1_0.models.AuthLoginWithAligenieUserInfoResponseBody;
import com.aliyun.aligeniessp_1_0.models.AuthLoginWithTaobaoUserInfoResponseBody;
import com.aliyun.aligeniessp_1_0.models.AuthLoginWithThirdUserInfoResponseBody;
import com.aliyun.aligeniessp_1_0.models.EcologyOpennessAuthenticateResponseBody;
import com.aliyun.aligeniessp_1_0.models.EcologyOpennessSendVerificationCodeResponseBody;
import com.aliyun.aligeniessp_1_0.models.FindUserlistToAuthLoginWithPhoneNumberResponseBody;
import com.google.gson.Gson;
import com.yx.cloud.MyApplication;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.CountryCodeBean;
import com.yx.cloud.bean.tmall.AuthorizedLogin;
import com.yx.cloud.databinding.BindTaobaoAccountActivityBinding;
import com.yx.cloud.product.laser.inxni.INXNIConstant;
import com.yx.cloud.product.laser.tuyapublic.BluetoothScanDeviceBean;
import com.yx.cloud.utils.AliHttpRequest_Runnable;
import com.yx.cloud.utils.CountryCodeUtils;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LanguageUtils;
import com.yx.cloud.utils.RegularCheckUtils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.ThreadUtils;
import com.yx.cloud.utils.ToastUtil;
import com.iot.common.utils.Event;
//import com.yx.robot.sdk.req.BluetoothScanDeviceBean;
import com.iot.common.utils.LogUtils;

import java.util.ArrayList;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class BindTaobaoAccountActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "BindTaobaoAccountActivity";
    private BindTaobaoAccountActivityBinding binding;
    private TimeCount time;
    private BluetoothScanDeviceBean deviceBean;
    private String network;
    private AliHttpRequest_Runnable runnable;
    private String mAccessToken, mCountryCode, deviceType;
    private int AligenieUserInfo;
    private MyApplication application;

    @Override
    public void onCreate() {
        binding = BindTaobaoAccountActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        if (runnable == null) {
            runnable = new AliHttpRequest_Runnable();
        }
        initData();
    }

    private void initData() {
        application = (MyApplication) this.getApplicationContext();
        //自动获取当前国家代码
//        String systemLanguage = LanguageUtils.getSystemLanguage(this);
//        String substring = systemLanguage.substring(3,5);
//        ArrayList<CountryCodeBean> codeList = CountryCodeUtils.getCountryCodeList(this);
//        if (codeList.size() > 0) {
//            for (int i = 0; i < codeList.size(); i++) {
//                if (substring.equals("" + codeList.get(i).getLocale())) {
//                    Log.d(TAG, "    IIIIIIIII-a-aaaaaaaaaaaaaaaaaaaaaa---" + codeList.get(i).getCode());
//                    mCountryCode = codeList.get(i).getCode() + "";
//                }
//            }
//        }
        mCountryCode = "+86";
        deviceBean = (BluetoothScanDeviceBean) getIntent().getSerializableExtra("bluetoothData");//保存的X5蓝牙信息
        network = getIntent().getStringExtra("network");
        deviceType = getIntent().getStringExtra("device_type");
        binding.etBindPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!"".equals(editable.toString().trim()) && binding.etEtBindVerificationCode.length() == 6) {
                    binding.btnBindNext.setEnabled(true);
                } else {
                    binding.btnBindNext.setEnabled(false);
                }

            }
        });
        binding.etEtBindVerificationCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!"".equals(binding.btnBindNext.toString().trim()) && editable.length() == 6) {
                    binding.btnBindNext.setEnabled(true);
                } else {
                    binding.btnBindNext.setEnabled(false);
                }

            }
        });

        binding.ivALiBindReturn.setOnClickListener(this);
        binding.tvBindTaobaoGetVerificationCod.setOnClickListener(this);
        binding.btnBindNext.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.iv_ALiBind_return) {
            Intent_utils.backIntent(this);
        } else if (id == R.id.tv_bindTaobaoGetVerificationCod) {
            //获取验证码
            binding.tmallBindAccountLottie.playAnimation();
            binding.tmallBindAccountLottie.setVisibility(View.VISIBLE);
            if (runnable == null) {
                runnable = new AliHttpRequest_Runnable();
            }
            AuthorizedLogin alogin = new AuthorizedLogin();
            alogin.setSceneCode(INXNIConstant.SCENE_CODE);
            alogin.setThirdUserType(INXNIConstant.THIRUSER_TYPE);
            alogin.setThirdUserIdentifier(INXNIConstant.USER_ID);
            runnable.initialization("auth_login", alogin);//获取验证码

        } else if (id == R.id.btn_bindNext) {
            //下一步
            binding.tmallBindAccountLottie.playAnimation();
            binding.tmallBindAccountLottie.setVisibility(View.VISIBLE);
            String phoneNum = binding.etBindPhoneNum.getText().toString().trim();
            String bindCode = binding.etEtBindVerificationCode.getText().toString().trim();
            if (!RegularCheckUtils.isMobile(phoneNum)) {
                Toast.makeText(this, getString(R.string.U_T_Un_NoFormat), Toast.LENGTH_SHORT).show();
                return;
            }
            AuthorizedLogin alogin = new AuthorizedLogin();
            alogin.setPhoneNumber(phoneNum);
            alogin.setRegion(mCountryCode);
            alogin.setVerificationCode(bindCode);
            alogin.setSessionId(INXNIConstant.SESSION_ID);
            if (runnable == null) {
                runnable = new AliHttpRequest_Runnable();
            }
            runnable.initialization("auth_login_user_list", alogin);//获取已授权登录用户列表

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_AUTHORIZED_LOGIN:
                //去 授权登录()检测
                if (event.isResult()) {
                    AuthLoginWithThirdUserInfoResponseBody body = (AuthLoginWithThirdUserInfoResponseBody) event.getContent();
                    Integer code = body.code;
                    Log.i(TAG, "授权登录 结果返回  :" + new Gson().toJson(body));
                    if (code == 5140001) {
                        //要去从新注册
                        INXNIConstant.SESSION_ID = body.getDataObj().getSessionId();

                        String phoneNum = binding.etBindPhoneNum.getText().toString().trim();
                        AuthorizedLogin alogin = new AuthorizedLogin();
                        alogin.setSessionId(INXNIConstant.SESSION_ID);
                        alogin.setPhoneNumber(phoneNum);
                        alogin.setRegion(mCountryCode);

                        runnable.initialization("verification_code", alogin);//获取验证码
                    } else {

                    }
                } else {
                    binding.tmallBindAccountLottie.pauseAnimation();
                    binding.tmallBindAccountLottie.setVisibility(View.GONE);
                    ToastUtil.show(BindTaobaoAccountActivity.this, "bindUser: " + getString(R.string.U_T_GetCode_No), Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_AUTHORIZED_LOGIN_VERIFICATION_CODE:
                //手机号授权登录,获取验证码结果返回
                binding.tmallBindAccountLottie.pauseAnimation();
                binding.tmallBindAccountLottie.setVisibility(View.GONE);
                if (event.isResult()) {
                    if (time == null) {
                        //获取验证码计时
                        time = new TimeCount(60000, 1000);
                        time.start();
                    }
                    EcologyOpennessSendVerificationCodeResponseBody verificationCode_body = (EcologyOpennessSendVerificationCodeResponseBody) event.getContent();
                    Log.i(TAG, "初次 1，手机号授权登录,获取验证码结果返回  :" + new Gson().toJson(verificationCode_body));
                } else {
                    String error_msg = (String) event.getContent();
                    ToastUtil.show(BindTaobaoAccountActivity.this, error_msg + " " + getString(R.string.U_T_GetCode_No), Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_AUTHORIZED_LOGIN_USER_LIST:
                //获取已授权登录的用户列表 结果返回
                if (event.isResult()) {
                    FindUserlistToAuthLoginWithPhoneNumberResponseBody body = (FindUserlistToAuthLoginWithPhoneNumberResponseBody) event.getContent();
                    if (body.getCode() == 5140003) {
                        //没有可以的用户,直接通过手机号生成精灵账号进行登录
                        if (runnable == null) {
                            runnable = new AliHttpRequest_Runnable();
                        }
                        runnable.initialization("phoneNumber_login", INXNIConstant.SESSION_ID);//通过手机号生成精灵账号进行登录
                    } else if (body.getCode() == 10000007) {
                        //验证码过期
                        binding.tmallBindAccountLottie.pauseAnimation();
                        binding.tmallBindAccountLottie.setVisibility(View.GONE);
                        ToastUtil.show(BindTaobaoAccountActivity.this, getString(R.string.U_T_Code_No), Toast.LENGTH_SHORT);
                    } else {
                        //有可用的用户
                        FindUserlistToAuthLoginWithPhoneNumberResponseBody.FindUserlistToAuthLoginWithPhoneNumberResponseBodyResult result = body.getResult();
                        String userIdentifier = result.getUserListToAuthLogin().get(0).getEncryptedUserIdentifier();
                        String userType = result.getUserListToAuthLogin().get(0).getUserType();
                        Log.i(TAG, "初次2，获取已授权登录的用户 sessionid :" + INXNIConstant.SESSION_ID);
                        Log.i(TAG, "初次2，获取已授权登录的用户 userIdentifier :" + userIdentifier);
                        Log.i(TAG, "初次2，获取已授权登录的用户 userType :" + userType);
                        if (runnable == null) {
                            runnable = new AliHttpRequest_Runnable();
                        }
                        if ("ALIGENIE".equals(userType)) {
                            //天猫精灵类型
                            runnable.initialization("genie_acciunt_login", userIdentifier);
                        } else if ("TAOBAO".equals(userType)) {
                            //淘宝类型
                            runnable.initialization("taobao_account_login", userIdentifier);
                        }
                    }
                    Log.i(TAG, "初次2，获取已授权登录的用户列表 结果返回  :" + new Gson().toJson(body));
                } else {
                    binding.tmallBindAccountLottie.pauseAnimation();
                    binding.tmallBindAccountLottie.setVisibility(View.GONE);
                    ToastUtil.show(BindTaobaoAccountActivity.this, "查询用户列表失败", Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_PHONE_NUMBER_AUTHORIZED_LOGIN:
                //通过手机号生成精灵账号进行登录
                if (event.isResult()) {
                    AuthLoginWithAligenieUserInfoGeneratedByPhoneNumberResponseBody body = (AuthLoginWithAligenieUserInfoGeneratedByPhoneNumberResponseBody) event.getContent();
                    String accessToken = body.getResult().getLoginStateAccessToken();
                    INXNIConstant.ACCESS_TOKEN = accessToken;
                    SharedPrefsUtil.putValue(this, "TMALL_ACCESS_TOKEN", "tmall_access_token", accessToken);
                    //获取鉴权成功后 有效时间，
                    Long expiredTimeLong = body.getResult().getExpiredTimeLong();
                    SharedPrefsUtil.putValue(this, "TMALL_AUTHENTICATION_TIME", "tmall_authentication_time", expiredTimeLong);
                    Log.i(TAG, "初次3，通过手机号生成精灵账号进行登录 结果返回  :" + new Gson().toJson(body));
                    //登录成功后，去鉴权拿userOpenId
                    AuthorizedLogin alogin = new AuthorizedLogin();
                    alogin.setAccessToken(accessToken);
                    runnable.initialization("authentication", alogin);//鉴权
                } else {
                    binding.tmallBindAccountLottie.pauseAnimation();
                    binding.tmallBindAccountLottie.setVisibility(View.GONE);
                    String error_msg = (String) event.getContent();
                    ToastUtil.show(BindTaobaoAccountActivity.this, error_msg, Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_TAOBAO_AUTH_LOGIN:
                //通过已有的淘宝账号登录
                if (event.isResult()) {
                    Log.d("taobao", "SECUSSE");
                    AuthLoginWithTaobaoUserInfoResponseBody body = (AuthLoginWithTaobaoUserInfoResponseBody) event.getContent();
                    String accessToken = body.getResult().getLoginStateAccessToken();
                    INXNIConstant.ACCESS_TOKEN = accessToken;
                    SharedPrefsUtil.putValue(this, "TMALL_ACCESS_TOKEN", "tmall_access_token", accessToken);
                    //获取鉴权成功后 有效时间，
                    Long expiredTimeLong = body.getResult().getExpiredTimeLong();
                    SharedPrefsUtil.putValue(this, "TMALL_AUTHENTICATION_TIME", "tmall_authentication_time", expiredTimeLong);

                    Log.i(TAG, "初次3，通过淘宝 类型 账号进行登录 结果返回  :" + new Gson().toJson(body));
                    //登录成功后，去鉴权拿userOpenId
                    AuthorizedLogin alogin = new AuthorizedLogin();
                    alogin.setAccessToken(accessToken);
                    runnable.initialization("authentication", alogin);//鉴权

                } else {
                    Log.d("taobao", "FAIL");
                    String error_msg = (String) event.getContent();
                    ToastUtil.show(BindTaobaoAccountActivity.this, error_msg, Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_GENIE_AUTH_LOGIN:
                //通过已有的天猫精灵账号登录
                if (event.isResult()) {
                    AuthLoginWithAligenieUserInfoResponseBody body = (AuthLoginWithAligenieUserInfoResponseBody) event.getContent();
                    String accessToken = body.getResult().getLoginStateAccessToken();
                    INXNIConstant.ACCESS_TOKEN = accessToken;
                    SharedPrefsUtil.putValue(this, "TMALL_ACCESS_TOKEN", "tmall_access_token", accessToken);
                    //获取鉴权成功后 有效时间，
                    Long expiredTimeLong = body.getResult().getExpiredTimeLong();
                    SharedPrefsUtil.putValue(this, "TMALL_AUTHENTICATION_TIME", "tmall_authentication_time", expiredTimeLong);
                    Log.i(TAG, "初次3，通过精灵 类型 账号进行登录 结果返回  :" + new Gson().toJson(body));
                    //登录成功后，去鉴权拿userOpenId
                    AuthorizedLogin alogin = new AuthorizedLogin();
                    alogin.setAccessToken(accessToken);
                    runnable.initialization("authentication", alogin);//鉴权
                } else {
                    String error_msg = (String) event.getContent();
                    ToastUtil.show(BindTaobaoAccountActivity.this, error_msg, Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_ACCESS_TOKEN_AUTHENTIATION:
                //新账号登录成功后去 鉴权拿userOpenid 结果返回
                binding.tmallBindAccountLottie.pauseAnimation();
                binding.tmallBindAccountLottie.setVisibility(View.GONE);
                if (event.isResult()) {
                    EcologyOpennessAuthenticateResponseBody body = (EcologyOpennessAuthenticateResponseBody) event.getContent();
                    Log.i(TAG, "初次4， : 鉴权AccessToken是否有效 结果返回  :" + new Gson().toJson(body));
                    Integer code = body.getCode();
                    String message = body.getMessage();
                    if (200 == code) {
                        //鉴权成功
                        //INXNIConstant.TMALL_LOGIN_STATE = true;
                        //application.setTmallLoginState(true);
                        EcologyOpennessAuthenticateResponseBody.EcologyOpennessAuthenticateResponseBodyResult result = body.getResult();
                        INXNIConstant.USER_OPEN_ID = result.getUserOpenId();
                        INXNIConstant.ENCODETYPE = result.getEncodeType();
                        INXNIConstant.ENCODEKEY = result.getEncodeKey();
                        INXNIConstant.SCENE_CODE = result.getSceneCode();
                        SharedPrefsUtil.putValue(this, "TMALL_USER_OPEN_ID", "tmall_user_open_id", INXNIConstant.USER_OPEN_ID);
                        //   ToastUtil.show(BindTaobaoAccountActivity.this, "该账号在有效期，不需要重新登录！", Toast.LENGTH_SHORT);

                        //获取关联的天猫账号信息
                        AuthorizedLogin authorizedLogin = new AuthorizedLogin();
                        authorizedLogin.setAccessToken(INXNIConstant.ACCESS_TOKEN);
                        runnable.initialization("aligenie_user_info", authorizedLogin);

                    } else {
                        //鉴权失败
                        //INXNIConstant.TMALL_LOGIN_STATE = false;
                        //application.setTmallLoginState(false);
                        SharedPrefsUtil.putValue(this, "TMALL_ALIGENIE_USER_INFO", "tmall_aligenie_user_info", "");
                        SharedPrefsUtil.putValue(this, "TMALL_ACCESS_TOKEN", "tmall_access_token", "");
                        ToastUtil.show(BindTaobaoAccountActivity.this, code + " : " + message, Toast.LENGTH_SHORT);
                    }
                }
                break;

            case Event.MESSAGE_TYPE_GET_ALIGENIE_USER_INFO:
                //获取三方绑定的精灵账号信息
                if (event.isResult()) {
                    String nickname = (String) event.getContent();
                    INXNIConstant.TMALL_USER_NICK_NAME = nickname;
                    Log.i(TAG, " 获取三方绑定的精灵账号信息 结果返回  :" + nickname);
                    SharedPrefsUtil.putValue(this, "TMALL_ALIGENIE_USER_INFO", "tmall_aligenie_user_info", nickname);

                    Intent intent = new Intent(this, SelectWIFIActivity.class);
                    intent.putExtra("network", "bluetooth");
                    intent.putExtra("source", "X5");
                    intent.putExtra("bluetoothData", deviceBean);//保存的X5蓝牙信息
                    intent.putExtra("device_type", deviceType);//设备型号
                    startActivity(intent);
                    finish();

                } else {
                    AligenieUserInfo++;
                    if (AligenieUserInfo < 3) {
                        //获取关联的天猫账号信息
                        AuthorizedLogin authorizedLogin = new AuthorizedLogin();
                        authorizedLogin.setAccessToken(INXNIConstant.ACCESS_TOKEN);
                        runnable.initialization("aligenie_user_info", authorizedLogin);
                    }
                }
                break;
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            binding.tvBindTaobaoGetVerificationCod.setClickable(false);
            binding.tvBindTaobaoGetVerificationCod.setText((millisUntilFinished / 1000) + "s" + getResources().getString(R.string.U_AgainGet_Btn));
        }

        @Override
        public void onFinish() {
            binding.tvBindTaobaoGetVerificationCod.setText(getResources().getString(R.string.U_GetCode_Btn));
            binding.tvBindTaobaoGetVerificationCod.setClickable(true);
            time = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (runnable != null) {
            ThreadUtils.getInstance().removeThread(runnable);
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
